package com.simonking.boot.mcp.client.config;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import io.modelcontextprotocol.client.McpSyncClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

@Slf4j
@Configuration
public class AIModelConfiguration {

    private   String DEFAULT_PROMPT = "你是一个博学的智能聊天助手，请根据用户提问回答！";
    private final List<McpSyncClient> mcpClients;

    public AIModelConfiguration(List<McpSyncClient> mcpClients) {
        this.mcpClients = mcpClients;
    }


    @Scheduled(fixedRate = 30000) // 每2分钟1次发送心跳 120000
    public void sendHeartbeat() {
        try {
            log.info("McpSyncClient ping... ");
            this.mcpClients.parallelStream().forEach(client -> {client.ping();});
        } catch (Exception e) {
            log.error("Heartbeat failed, triggering reconnect",e);
        }
    }

    /**
     *
     * @param model  语言大模型
     * @param toolCallbackProvider MCP工具
     * @return
     */
    @Bean
    public ChatClient chatclient(DashScopeChatModel model, ToolCallbackProvider toolCallbackProvider) {
        return ChatClient.builder(model)//阿里千问大模型
                .defaultSystem(DEFAULT_PROMPT)
                // 在使用 Chat Memory 时，需要指定对话 ID，以便 Spring AI 处理上下文。
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(new InMemoryChatMemory())
                )
                // 实现 Logger 的 Advisor
                .defaultAdvisors(
                        new SimpleLoggerAdvisor()
                )
                // 设置 ChatClient 中 ChatModel 的 Options 参数
                .defaultOptions(
                        DashScopeChatOptions.builder()
//                                .withTopP(0.7)
                                .build()
                )
                //# deepseek-r1 大模型不支持MCP配置. #spring.ai.dashscope.chat.options.model=deepseek-r1
                .defaultTools(toolCallbackProvider.getToolCallbacks())//MCP工具配置
                .build();
    }
}
